from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
from django.template import loader
from django.views.generic import CreateView, DetailView

from jobs.models import Job, Resume


def joblist(request):
    job_list = Job.objects.order_by('job_type')
    context = {"job_list": job_list}

    for job in job_list:
        job.city_name = job.get_job_city_display()
        job.job_type = job.get_job_type_display()
    # return HttpResponse(template.render(context))
    return render(request, 'joblist.html', context)


def detail(request, job_id):
    try:
        job = Job.objects.get(pk=job_id)
        job.city_name = job.get_job_city_display()
    except Job.DoesNotExist:
        raise Http404("Job does not exists")

    return render(request, 'job.html', {"job": job})


class ResumeCreateView(LoginRequiredMixin, CreateView):
    template_name = 'resume_form.html'
    success_url = '/jobs/'
    model = Resume
    fields = ["username", "city", "phone", "email", "apply_position", "gender", "bachelor_school",
              "master_school", "major", "degree", "candidate_introduction", "work_experience", "project_experience"]

    # 从url请求参数带入默认值
    def get_initial(self):
        initial = {}
        for x in self.request.GET:
            initial[x] = self.request.GET[x]
        return initial

    def form_invalid(self, form):
        cv_object = form.save(commit=False)
        cv_object.applicant = self.request.user
        cv_object.save()
        return HttpResponseRedirect(self.get_success_url())


class ResumeDetailView(DetailView):
    model = Resume
    template_name = 'resume_detail.html'
